<template>
  <div class="rule-details innerPageTable-out-flex">
    <Modal
        v-model="modal1"
        @on-ok="ok"
        @on-cancel="cancel">
        <p slot="header">{{titleModle}}</p>
      <Form :label-width="90">
        <Form-item label="备注/意见">
          <Input type="textarea" v-model="messages" :rows="4"></Input>
        </Form-item>
      </Form>
    </Modal>
    <Modal
        v-model="modal2"
        title="驳回"
        @on-ok="ok2"
        @on-cancel="cancel2">
      <Form :label-width="90">
        <Form-item label="驳回节点">
        <Select  v-model="taskDefKeys">
              <Option v-for="item in optionList"
              :key="item.taskDefKey"
              :value="item.taskDefKey">{{item.taskNodeName}}</Option>
            </Select>
      </Form-item>
        <Form-item label="备注/意见">
          <Input type="textarea" v-model="messages2" :rows="4"></Input>
        </Form-item>
      </Form>

    </Modal>

    <div class="content_top">
      <div class="cus_titles"><span class="base"></span>规则组信息</div>
      <detail-form ref="formDetail" :form-data="searchData" :is-disabled="!isShow1  && !(this.title ==='新建信息' || this.title === '跳转新建')">
      </detail-form>
      <div class="cus_titles"><span class="rulebase"></span>规则明细</div>
      <InnerPageTable ref="listTable" :config="pageTableConfig" class="page_table">
        <div slot="table-bar" v-if="!isDisabled1 && !(this.title ==='详情信息(只读)')">
          <Button @click.native="add" :disabled="!isShow1  && !(this.title ==='新建信息' || this.title === '跳转新建')">新建</Button>
          <Button type="error" @click.native="del" :disabled="!isShow1  && !(this.title ==='新建信息' || this.title === '跳转新建')">删除</Button>
          <Button v-show="false"></Button>
        </div>
      </InnerPageTable>
    </div>
    <!-- 功能按钮群 -->
    <div class="btn_box" v-if="!isDisabled1">
<!--      <Button type="primary" @click="saveInfo" v-if="isShow1  && this.title ==='新建信息' || this.title === '跳转新建'">保存</Button>-->
      <Button type="primary" @click="saveInfo" v-if="isShow1  && this.title ==='新建信息' || this.title === '跳转新建'">保存</Button>
      <Button type="primary" @click="updateInfo" v-if="isShow1 && this.title ==='详情信息' ">保存</Button>
      <!-- <Button type="primary" @click="submitHandle('提交')" v-if="isShow">提交</Button>
      <Button type="primary" @click="submitHandle2('重新提交')" v-if="isShow2">重新提交</Button> -->
      <!-- <Button type="primary" @click="flowHandle" v-if="processId">流程</Button> -->
      <!-- <Button type="primary" @click="pressHandle('审核')" v-if="isShow3">审核</Button>
      <Button type="primary" @click="backHandle"  v-if="isShow3">驳回</Button>
      <Button type="primary" @click="backHandle1" v-if="isShow4">撤回</Button> -->
      <Button type="default" @click.native='backHandle2' >返回</Button>
    </div>
  </div>
</template>

<script>
import DetailForm from './DetailForm'
import addModal from "./AddModal";
import flowImage from "@/components/flowImage";
import listDetails from "./ListDetails.vue";

import { generateColumns, configForm} from "./detail-constants"
import ruleBaseAPI from "@/api/ruleBaseApi.js"
import ruleListAPI from "@/api/ruleListApi.js";
import todoListAPI from "@/api/todoListApi.js"
import { mixin } from '../mix/mixin'

export default {
  name: 'list-details',
  mixins: [mixin],
  components:{
    detailForm: DetailForm,
    addModal,
    listDetails
    // processes
  },
  props: {
    title: {
      type: String,
      default: ''
    },
    codeInt:{
      type: String,
      default: ''
    },
    idInt:{
      type: String,
      default: ''
    },
    detailId:{
      type: String,
      default: ''
    },
    groupCode:{
      type: String,
      default: ''
    },
    bpmnState: {
      type: Number,
      default:null
    },
    isDisabled: {
      type: Boolean,
      default: false
    },
    isDisabled1: {
      type: Boolean,
      default: false
    },
    rowDetail: {},
  },
  data() {
    return {
      titleModle:'',//按钮弹窗标题
      modal1: false,
      modal2: false,
      optionList: [],      // 流程节点
      pageTableConfig: {
        loadDataFn: this.getTableList,
        columns: generateColumns.bind(this)(),
        autoFirst: true,
        autoMaxHeight:false,//关于高度
        selectionAreaItem: { key: "id", title: "userName" },
        allSelection: [],
        initParam: {
          "describes": "",
          "groupCodeList": [],
          "idList": [],
          "parentList": [],
          "ruleIdentifyColumn": "",
          "ruleTableName": "",
          "stateList": [],
          "title": ""
        }
      },
      detailInfo:[],
      formValidate:{},
      processId: '',//流程id

      pressesData: null,//获取接口的流程数据
      taskId:'',//审核需要传的参数id
      messages: '',//审核需要传的参数意见
      messages2: '',//驳回需要传的参数意见
      taskDefKeys:'',//驳回需要传的参数
      taskNodeData: null,//获取可驳回的流程节点
      // 控制按钮显示
      isUndo: true,//判断能否撤回流程
      userIds:[],
      userId:'',//当前用户的id
      createUserId: '',
      optionListN: []
    }
  },
  computed: {
    // ...mapState('sasspWeb', state),
    searchData() {
      const arr = configForm.bind(this)()
      const index = arr.findIndex(item => item.field === 'bpmnState')
      if (index > -1) {
        arr.splice(index, 1)
      }
      return arr
    },
    //是否展示提交按钮
    isShow() {
      return  this.bpmnState == null && this.processId == null && this.userId === this.createUserId
    },
    //是否展示保存（修改）按钮
    isShow1() {
      return ( this.codeInt || this.bpmnState == null && this.userId == this.createUserId) || (this.bpmnState === 1 && !!this.pressesData &&  this.pressesData.taskDefKey === 'start_task_user_activity' && this.userIds.includes(this.userId))
    },

    //是否展示重新提交按钮
    isShow2() {
      return this.bpmnState === 1 && this.processId != null && !!this.pressesData && this.pressesData.taskDefKey === 'start_task_user_activity' && this.userIds.includes(this.userId)
    },
    //是否展示审批、驳回按钮
    isShow3() {
      return this.bpmnState === 1 && this.processId != null && !!this.pressesData && this.pressesData.taskDefKey != 'start_task_user_activity' && this.userIds.includes(this.userId)
    },
    //撤回
    isShow4() {
      return this.bpmnState === 1 && this.processId != null && this.userId==this.createUserId  && !!this.pressesData && this.pressesData.taskDefKey != 'start_task_user_activity' && this.isUndo
    },
    optionListUnit() {
      return this.optionListN;
    },
  },
  created() {
    //获取用户id
    $http.post('/apis/mgt/security/getLoginData').then(res => {
      this.userId = res.data.userBasicVo.id
     // 获取用户信息
     ruleBaseAPI.detailUserInfo({ id: this.userId }).then(res => {
        console.log(res.data);
        let crsrmPurchaser_Name = [];
        let crsrmPurchaser_Sbu = [];
        crsrmPurchaser_Sbu = this.getTaskId(res.data.crsrmPurchaserSbu);

        crsrmPurchaser_Sbu.forEach(item => {
          this.optionListN.push({
            label: this.crsrm_purchaser_sbu.find(x => x.value === item).label,
            value: item
          });
        });
      });
    })
    if (this.title === '跳转新建' && this.rowDetail) {
      this.searchData.forEach((item) => {
        for (let i in this.rowDetail) {
          if (item.field == i) {
            item.value = this.rowDetail[i]+''
          }
        }
      })

    }
   //如果是详情进入时
    if (this.rowDetail && this.detailId) {
      this.searchData.forEach((item) => {
        for (let i in this.rowDetail) {
          if (item.field == i) {
            item.value = this.rowDetail[i]+''
          }
        }
      })
      // this.pageTableConfig.autoFirst=true
      this.processId = this.rowDetail.processId
      this.createUserId=this.rowDetail.createUserId
      if (this.processId) {
        //查询流程实例最新的节点id和任务处理人
        todoListAPI.processNode({ id: this.processId }).then(res => {
          if (res.data != null) {
            this.pressesData = res.data
            this.userIds = this.getTaskId(this.pressesData.userIds)
            this.taskId= this.getTaskId(res.data.taskIds)[0]
          }

        })

        //查询可以退回的流程节点
        todoListAPI.processRejectNode({ id: this.processId }).then(res => {
          this.taskNodeData = res.data
          this.optionList=this.taskNodeData
        })

        //判断能否撤回流程
        todoListAPI.processUndoCheck({ id: this.processId }).then(res => {
          this.isUndo= res.data
        })
      }
    } else {
      //新建页面生成的编码
        this.searchData.forEach((item) => {
          if (item.field == 'code') {
            item.value = this.codeInt
          }
        })
    }

  },
  mounted() {
    this.init()
  },

  methods: {
    //字符串转数组的方法
    getTaskId(taskIds) {
      // return taskIds.split(',')[0]
      return taskIds.split(',')
    },
    getTableList(tableObj) {
      let { responseProcess, initParam, param } = tableObj;
      const params = {
        ...param,
        ...initParam
      }
      this.pageTableConfig.initParam.parentList.push(this.idInt)
      ruleBaseAPI.queryDetails(params).then(res => {
        responseProcess(res.data);
      })
/*      if (!this.detailId && !this.groupCode && this.title !== '跳转新建') {
        //新建时-->获取表数据
        this.pageTableConfig.initParam.parentList.push(this.idInt)
        ruleBaseAPI.queryDetails(params).then(res => {
        responseProcess(res.data);
        })
      }
      if (this.title === '详情信息' || this.title === '详情信息(只读)') {
        //详情时-->获取表数据
        this.pageTableConfig.initParam.parentList.push(this.detailId)
        ruleBaseAPI.queryDetails(params).then(res => {
        responseProcess(res.data);
        })
      }
      // if (this.title === '列表详情(只读)') {
      if (this.title === '跳转新建') {
        //规则库列表--》详情时-->获取表数据
        this.pageTableConfig.initParam.parentList.push(this.detailId)
        ruleListAPI.getScriptPage(params).then(res => {
        responseProcess(res.data);
        })
      }*/

    },
    //数组转对象方法
    arrobj(formData){
      return formData.reduce((obj, item) => {
        obj[item.field] = item.value
        return obj
      },{})
    },
    // 新建时保存
    saveInfo() {
      this.$refs.formDetail.$refs.createForm.validate((valid) => {
        if (valid) {
          const dataForm = this.$refs.formDetail.detailData.formData
          this.formValidate = this.arrobj(dataForm)
          // this.formValidate = this.arrobj(this.searchData)
          this.$confirm.warning(this.$t("确定变更吗？")).then(() => {
            this.formValidate.id = this.idInt
            ruleBaseAPI.createList(this.formValidate).then(res => {
              this.$message.success({
                content: this.$t("保存成功"),
                duration: 3
              });
              // this.resetHandle()
              this.backHandle2()
            })
          })
          // this.$Message.success('Success!');
        } else {this.$Message.error('检查是否完整填写相关内容！！');}
      })

    },
    //详情时--修改
    updateInfo() {
      this.$refs.formDetail.$refs.createForm.validate((valid) => {
        if (valid) {
          const dataForm = this.$refs.formDetail.detailData.formData
          this.formValidate = this.arrobj(dataForm)
          // this.formValidate = this.arrobj(this.searchData)
          this.$confirm.warning(this.$t("确定修改吗？")).then(() => {
        if (this.detailId && this.groupCode) {
          this.formValidate.version = this.rowDetail.version
          this.formValidate.id=this.detailId
          ruleBaseAPI.updateList(this.formValidate).then(res => {
            this.$message.success({
                content: this.$t("修改成功"),
                duration: 3
            });
            this.backHandle2()
          })
        }
      })
         }else{this.$Message.error('检查是否完整填写相关内容！！');}
       })

    },


    ok() {
     let params={
        "message":this.messages,
        "taskId": this.taskId,
        "values": {}
      }
      if (this.titleModle == '审核') {
        todoListAPI.processPass(params).then(res => {
          this.$Message.success(res.message);
        })
        this.resetHandle()
      }
      if (this.titleModle == '重新提交') {
        this.$confirm.warning(this.$t("确定重新提交吗？")).then(() => {
          todoListAPI.processSubmit(params).then(res => {
            this.$Message.success(res.message);
            this.resetHandle()
      })
         })

      }

    },
    cancel () {},
    ok2() {
      let params={
          "message":this.messages2,
          "procInstId": this.processId,
          "taskDefKey": this.taskDefKeys
      }
      this.$confirm
        .warning(this.$t("确定撤回吗？")).then(() => {
          todoListAPI.processReject(params).then(res => {
            this.$Message.success(res.message);
            this.resetHandle()
      })
         })

    },
    cancel2 () {},
     //重新提交
    submitHandle2(titleModle) {
      this.titleModle=titleModle
      this.modal1 = !this.modal1
     },
    //提交按钮事件
    submitHandle(titleModle) {
      const params = {
        "describes": this.rowDetail.describes,
        "id": this.detailId,
        "taskId": this.rowDetail.taskId
      }
      if (!this.detailId && !this.groupCode) {
        params.id=this.idInt
      } else { params.id = this.detailId }
      this.$confirm
        .warning(this.$t("确定提交吗？")).then(() => {
          ruleBaseAPI.submitList(params).then(res => {
        this.$message.success({
              content: this.$t("提交成功"),
              duration: 3
        });
        this.resetHandle()
      })

        })

    },
    // 驳回按钮事件
    backHandle() {
      this.modal2 = !this.modal2
    },

    // 审核按钮事件
    pressHandle(titleModle) {
      this.titleModle=titleModle
      this.modal1 = !this.modal1
    },
    // 撤回
    backHandle1() {
      if (this.isUndo) {
        this.$confirm
          .warning(this.$t("确定撤回吗？")).then(() => {
            todoListAPI.processUndo({id: this.processId }).then(res => {
              this.resetHandle()
        })

           })

     }

    },
    //规则列表更变后页面返回按钮
    backHandle2() {
      this.$emit("Close");
    },
    //流程历史
    flowHandle() {
      new this.$pageModal(flowImage, { props: { id: this.rowDetail.processId } })
    },
    //新建
    add() {
      new this.$pageModal(
        addModal,
        {
          props: { groupCode: this.groupCode, parent: this.idInt, codeInt: this.codeInt, title: '新建(详情)' }
        },
        () => {
          this.resetHandle();
          // window.alert("关闭 pageModal 对话框时的回调");
        }
      )
/*      //新建页面---->新建按钮
      if (!this.detailId && !this.groupCode) {
        new this.$pageModal(
          addModal, { props: { codeInt: this.codeInt, parent: this.idInt, title: '新建' } },
          () => {
            this.resetHandle();
            // window.alert("关闭 pageModal 对话框时的回调");
          }
        )
      } else {
        //详情页面---->新建按钮
        new this.$pageModal(
          addModal,
          {
            props: { groupCode: this.groupCode, parent: this.detailId, title: '新建(详情)' }
          },
          () => {
            this.resetHandle();
            // window.alert("关闭 pageModal 对话框时的回调");
          }
        )

       }*/

    },

    init() {
      this.$emit("SetTitle", this.title);
    },
    // 删除
    del() {
      let allSelected = this.$refs["listTable"].allSelection;
      if (allSelected.length == 0) {
        this.$message.error(this.$t("请至少选择一套数据"));
        return;
      }
      this.$confirm
        .warning(this.$t("确定删除后，无法恢复！"))
        .then(() => {
          const idList = allSelected.map(user => user.id);
          ruleBaseAPI.deleteDetails({idList}).then(res => {
            this.$message.success({
              content: this.$t("删除成功"),
              duration: 3
            });
            this.$refs["listTable"].allSelection = [];
          });
          this.tableHandle()
        })
        .catch(_ => _);
    },
    //详情
    detailHandle(row) {
      let detailRow = row
      let detailId = row.id
      let groupCode = row.code
      // 查询
      let params={
        "codeList": [],
        "dataItemName": "",
        "dataSubject": "",
        "describes": "",
        "functionModules": "",
        "idList": [],
        "stateList": [],
        "title": ""
      }
      params.idList.push(detailId)
      if (this.isDisabled1 || this.title === '列表详情(只读)') {
        ruleListAPI.getScriptList(params).then(res => {
          detailRow = res.data[0]
        })
          new this.$pageModal(
            addModal, { props: { detailRow, detailId, groupCode, isDisabled: true, title: '详情(只读)' } },
            // 关闭时的回调
          () => {
            this.resetHandle()
              }
            )
      } else {
        ruleBaseAPI.queryList2(params).then(res => {
          detailRow = res.data[0]
        })
        new this.$pageModal(
          addModal, { props: { detailRow, detailId, groupCode, isDisabled: true, title: '详情' } },
          // 关闭时的回调
          () => {
            this.resetHandle()
              }
        )
      }
    },
  }
}

</script>

<style lang="less" scoped>
.rule-details {
  height: 100%;

  .content_top {
    height: calc(100% - 50px) !important;
    overflow-y: scroll;
  }
}
.cus_titles {
  display: flex;
    align-items: center;
    padding:0 10px;
    //margin: -10px;
    margin-bottom: 10px;
    height: 40px;
    line-height: 40px;

    font-size: 14px;
    color: #262626;
    letter-spacing: 0;
    text-align: left;
    font-weight: 400;
    background: #F8F9FB;
    position: relative;
    .base {
      width: 17px;
      height: 18px;
      margin-right: 10px;
      background: url("../../../asset/icons/rulebase.svg") no-repeat center;
      background-size: cover;
    }
    .rulebase {
      width: 17px;
      height: 18px;
      margin-right: 10px;
      background: url("../../../asset/icons/rulebase1.svg") no-repeat center;
      background-size: cover;
    }
  }
.page_table{
  min-height: 500px !important;
}
.btns{
  display: flex;
  justify-content: end;
}
.btn_box {
    text-align: right;
    background: #ffffff;
    margin-right: 60px;
    margin-top: 10px;
  }
  .btn_box > *{
    margin-left: 10px;
    margin-bottom: 5px;

  }
/deep/.ivu-input[disabled], /deep/.ivu-select-disabled .ivu-select-selection, /deep/.ivu-select-single{
  color: #666F83 !important;
}
</style>


